package com.tomcat.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 24/9/2020
 */
public class ResourcesUtils {

    public static String getAbsoluteResourcePath(String url) {
        String path = ResourcesUtils.class.getResource("/").getPath();
        return path.replace("\\\\", "/") + url;
    }

    public static void outPutResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        // 先输入请求头
        outputStream.write(HttpHeaderUtils.httpStatus200(resourceSize).getBytes());

        // 已读取文件长度
        long written = 0;
        // 计划每次缓存的长度
        int byteSize = 1024;
        // 存放读取出来的文件字节流
        byte[] bytes = new byte[resourceSize];
        while (written < resourceSize) {
            // 说明剩余读取文件长度小于1024，按照剩余内容长度进行读取
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }


    }

    public static void main(String[] args) {
        String absoluteResourcePath = getAbsoluteResourcePath("index.html");

        System.out.println(absoluteResourcePath);
    }
}
